var WIS = function(){
	if(!window.console){
		window.console = {log:function(){
		}};
	}
	var WIS_FLASH_PATH = "http://cdn.aodianyun.com/wis/wis.swf";
	var WIS_H5DRAW_PATH = "./jsrel/draw.js";
	var WIS_FLASH_INSTALL_PATH = "http://cdn.aodianyun.com/wis/playerProductInstall.swf";
	
	var opt_ = {
		maxPage:18,
		curPage:0
	};
	function parseHistory(obj){
		var hasDif = false;
		for(var i =obj.length-1;i >= 0; i--){
			try{
				var data = eval("("+obj[i]+")");
				if (data.docId == opt_.docId){
					if(data.page != null){
						hasDif = true;
					}
					drawQueue_.Push(data);
				}
			}catch(err){
				console.log(err);
			}
		}
		if(!hasDif) {
			drawQueue_.Push({page:1});
		}
	}
	function syncData(data) {
		data.page = opt_.curPage;
		data.width = opt_.width;
		data.height = opt_.height;
		data.clientid = clientid_;
		if(opt_.useFlash){
			var str = opt_.drawFactory.JSONEncode(data);
		}else{
			var str = JSON.stringify(data);
		}
		opt_.api.syncDraw({
			wisId:opt_.wisId,
			body:str,
			success:function(){},
			failure:function(){}
		});
    }
  	var clientid_ = null;
    function connect(){
    	if(opt_.useFlash){
    		window.__onMessage = onMessage;
    		window.__onClose  = function(){
    			try{if(opt_.onConnectClose)opt_.onConnectClose();}catch(err){console.log(err);}
    		};
    		window.__onConnectSuc = function(){
    			try{if(opt_.onConnect)opt_.onConnect();}catch(err){console.log(err);}
    		};
    		window.__onReconnect = function(){
    			try{if(opt_.onReconnect)opt_.onReconnect();}catch(err){console.log(err);}
    		};
    		clientid_ = opt_.drawFactory.connect("",opt_.subKey,opt_.topic,"");
    	}else{
    		wsconnect();
    	}
    }
    function wsconnect(){
    	if(!clientid_){
    		clientid_ ="ws2-"+Paho.MQTT.NewGuid();
    	}else{
    		try{if(opt_.onReconnect)opt_.onReconnect();}catch(err){console.log(err);}
    	}
    	var mqttClient_ = new Paho.MQTT.Client("mqtt.dms.aodianyun.com", Number(8000),clientid_ );
            mqttClient_.onConnectionLost = function(responseObject){
            	if (responseObject.errorCode !== 0){
            	 	if(mqttClient_ != null ){
	    				try{
			    			mqttClient_.disconnect();
			    		}catch(err){

			    		}
		    			mqttClient_ = null;
						setTimeout(wsconnect,100);
    				}	
				}
			};
            mqttClient_.onMessageArrived = function(message){
            	onMessage(message.destinationName,message.payloadString);
			}
            mqttClient_.connect({
				timeout:10, // connect timeout
				userName:"",
				password:opt_.subKey,
				keepAliveInterval:60 , // keepalive 
				cleanSession:false , // 
				onSuccess:function(){
					mqttClient_.subscribe("__present__"+opt_.topic,{qos:1});
					mqttClient_.subscribe(opt_.topic,{qos:1});
					mqttClient_.subscribe(opt_.topic+"_C",{qos:1});
					try{if(opt_.onConnect)opt_.onConnect();}catch(err){console.log(err);}
				},
				onFailure:function(err){
					try{if(opt_.onConnectClose)opt_.onConnectClose();}catch(err){console.log(err);}
					setTimeout(wsconnect,1000);
				}
			});
    }
    function onMessage(topic,msg){
    	try{
    		console.log(msg);	
			var data = eval('('+msg+')');
			if(topic == opt_.topic){
				if(data.clientid == clientid_) {
					return;
				}
				drawQueue_.Push(data);
			}else if (topic == "__present__"+opt_.topic){
				total_ = data.total;
				if(opt_.updateUser != null){
	    			opt_.updateUser(data.total,data);
	    		}
			}else if (topic == opt_.topic + "_C"){
				try{
					msg =  eval('('+msg+')');
				}catch(err){}
				if(opt_.onCustomMessage != null){
	    			opt_.onCustomMessage(msg);
	    		}
			}		
    	}catch(err){
    		console.log(err);
    	}
    }
    function parseScale(message){
    	var sx = opt_.width/message.width;
    	var sy = opt_.height/message.height;
    	if(message.start){
    		message.start.x *= sx;
    		message.start.y *= sy;
    	}
    	if(message.end){
    		message.end.x *= sx;
    		message.end.y *= sy;
    	}
    	if(message.plots){
    		for(var i=0; i<message.plots.length/2; i++) {
	    		message.plots[2*i] *= sx;
	    		message.plots[2*i+1] *= sy;
	   	 	}
    	}
    }

    var drawQueue_ = new DrawQueue();
    function DrawQueue(){
    	this.queue_ = [];
    	this.drawing = false;
    }
    DrawQueue.prototype.Push = function(message){
    	if(message != null){
    		this.queue_.push(message);
    		this.drawQueue();
    	}
    }
	DrawQueue.prototype.drawQueue = function(){
    	if(this.drawing) return;
    	this.drawing = true;
    	while(this.queue_.length > 0 ){
    		var self =this;
	    	message = this.queue_.shift();
	    	if( message.page != null &&　message.page != opt_.curPage ){
				opt_.curPage = message.page;
				delete message.page;
				if(message.cmd != "page"){
					this.queue_.unshift(message);
				}
				ShowPage({
					pageUrl:message.pageUrl,
					success:function(){
						self.drawing = false;
						self.drawQueue();
					},
					failure:function(){
						self.drawing = false;
						self.drawQueue();
					}
				});
				return;
	    	}
	    	if(message.cmd == "draw"){
	    		parseScale(message);
				var r = opt_.drawFactory.RecvDraw(message);
			}
			if(message.cmd == "clear"){
				opt_.drawFactory.Clear();
			}
			if(message.cmd == "choseDoc"){
				if(opt_.docId != message.docId){
					opt_.docId = message.docId;
					opt_.api.getDocInfo({
						docId:opt_.docId,
						success:function(info){
							initDocInfo(info);
							opt_.curPage = 1;
							ShowPage({
								success:function(){
									self.drawing = false;
									self.drawQueue();
								},
								failure:function(){
									self.drawing = false;
									self.drawQueue();
								}
							});
						},
						failure:function(obj){
							self.drawing = false;
							self.drawQueue();
						}
					});
					return;
				}
			}
    	}
    	this.drawing = false;
    }
    function initDocInfo( info ){
    	opt_.pdf = info.pdfUrl;
		opt_.maxPage = info.page;
		opt_.whs = info.width/info.height; 
		resize();
		try{
			if(opt_.onDocLoad)opt_.onDocLoad({fileName:info.fileName,id:info.id,page:info.page,width:info.width,height:info.height});
		}catch(err){
			console.log(err);
		}
    }
    function resize(){
    	//s1 = opt_.orgWidth/opt_.orgHeight;
    	/////////////////
    	s1 = opt_.whs;
    	if(s1<=1){
    		if(opt_.orgWidth == 0)
    			opt_.orgWidth = 784;
    	}else{
    		if(opt_.orgWidth == 0)
    			opt_.orgWidth = 1000;
    	}
    	opt_.orgHeight = opt_.orgWidth/opt_.whs;
        ////////////////
    	
		opt_.width = opt_.orgWidth;
		opt_.height = opt_.orgHeight;
		if(s1 > opt_.whs){
			opt_.width =  opt_.whs * opt_.orgHeight;
			opt_.width = opt_.width << 0;
		}else{
			opt_.height = opt_.orgWidth / opt_.whs;
			opt_.height = opt_.height << 0;
		}
		opt_.drawFactory.width = opt_.width;
		opt_.drawFactory.height = opt_.height;
		var data = {
			top:( opt_.orgHeight - opt_.height )/2,
			left:( opt_.orgWidth - opt_.width )/2,
			width:opt_.width,
			height:opt_.height
		};
		$("#"+opt_.container)[0].style.paddingTop =  data.top + "px";
		$("#"+opt_.container)[0].style.marginLeft =  data.left + "px";
		opt_.drawFactory.Resize(data);
		/////////////////////////////////////
		$(".boardBox").height(data.height);
		$("#wis_context").height(data.height);
		if($("#wis_context_inner")) $("#wis_context_inner").height(data.height);
		$(".leftBox").height(data.height + 58);
		$(".content").height(data.height + 58 +2);
		$(".mainBody").height((data.height + 58 +2)/0.95);
		
		$(".boardBox").width(data.width);
		$("#wis_context").width(data.width);
		if($("#wis_context_inner")) $("#wis_context_inner").width(data.width);
		$(".leftBox").width(data.width +76);
		$(".content").width(data.width + 76);
		$(".boardView").width(data.width + 76);
		$(".rightBox").css("margin-left",(data.width + 76 + 10) + "px");
		var sumwidth = data.width +76 + 10 + 280;
		var screenwidth = window.screen.width;
		if(sumwidth<screenwidth){
			$(".topBar").width(screenwidth-20);
		}else{
			$(".topBar").width(sumwidth);
		}
		//////////////////////////////
    }
	


	function ShowPage(option){
		if(!option) option = {};
		function callback(){
			if(option&&option.success)option.success();
		}
		if(opt_.curPage <= 0){
			callback();
			return;
		}
		var url = opt_.pdf + '?page/'+opt_.curPage+'/density/150/quality/80/resize/'+opt_.width;
		var tmpPage = opt_.curPage;
		
		if(opt_.useFlash){
			opt_.callBackIndex++;
			opt_.callBackMap[opt_.callBackIndex] = callback;
		}
		if(option.pageUrl != null){
			var pageUrl = option.pageUrl;
			if( option.pageUrl == "nodraw"){
				pageUrl = null;
			}
			opt_.drawFactory.ShowBg({
				url:url,
				pageUrl:pageUrl,
				index:opt_.callBackIndex,
				success:callback,
				failure:callback
			});
			try{
				if(opt_.onPageChange)opt_.onPageChange(opt_.curPage,opt_.maxPage);
			}catch(err){
				console.log(err);
			}
			return;
		}
		opt_.api.getPageInfo({
			docId:opt_.docId,
			page:tmpPage,
			success:function(data){
				var pageUrl = null;
				if(data.url){
					pageUrl = data.url+"?"+data.ts;
				}

				opt_.drawFactory.ShowBg({
					url:url,
					pageUrl:pageUrl,
					index:opt_.callBackIndex,
					success:callback,
					failure:callback
				});
				try{
					if(opt_.onPageChange)opt_.onPageChange(opt_.curPage,opt_.maxPage);
				}catch(err){
					console.log(err);
				}
			},
			failure:function(err){
				opt_.drawFactory.ShowBg({
					url:url,
					index:opt_.callBackIndex,
					success:callback,
					failure:callback
				});
				try{
					if(opt_.onPageChange)opt_.onPageChange(opt_.curPage,opt_.maxPage);
				}catch(err){
					console.log(err);
				}

			}
		});
		
	}
	function syncAndShowPage(page,option){
		opt_.api.syncPage({
			wisId:opt_.wisId,
			page:page,
			success:function(info){
				opt_.curPage = page;
				if(info){
					if(!option){
						option = {};
					};
					option.pageUrl = info.pageUrl;
				}
				ShowPage(option);
			},
			failure:function(){
				if (option && option.failure){
					option.failure();
				}
			}
		});
	}
	function canvasSupport() {
		if(window.WebSocket){
			return !!document.createElement('canvas').getContext;
		}else{
			return false;
		}
	}

	function loadInfo(){
		opt_.api.getWisInfo({
			wisId:opt_.wisId,
			success:function(data){
				opt_.docId  = data.docId;
				opt_.topic = data.topic;
				opt_.subKey = data.subKey;
				data.secKey  = "demo";
				opt_.secKey = data.secKey;
				if(opt_.docId == "" || opt_.docId == null){
					opt_.loaded = true;
					opt_.success();
					connect();
				}else{
					opt_.api.getDocInfo({
	
						docId:opt_.docId,
						success:function(info){
							initDocInfo(info);
							opt_.loaded = true;
							opt_.success();
							opt_.api.getHistory({
								wisId:opt_.wisId,
								success:function(data){
									parseHistory(data)
									connect();
								},
								failure:function(){
									opt_.curPage = 1;
									ShowPage();
									connect();
								}
							});
						},
						failure:function(text){
							if(typeof text == "string" ){
								opt_.failure("获取文档信息失败:"+text);
							}else{
								opt_.failure("获取文档信息失败:"+text.responseText);
							}
							
						}
					});
				}
			},
			failure:function(text){
				if(typeof text == "string" ){
					opt_.failure("获取白板信息失败:"+text);
				}else{
					opt_.failure("获取白板信息失败:"+text.responseText);
				}
			}
		});
	}
	function LoadWsAndDrawJs ( ){
		var hasPaho = (typeof Paho !="undefined");
		var hasDrawJs = (typeof WISDRAW !="undefined");
		if(!hasPaho) {
			var s = document.createElement('script');
			s.type = 'text/javascript';
			s.async = false;
			s.src = 'http://cdn.aodianyun.com/dms/ws.js';
			s.charset = 'UTF-8';
			(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(s);
		}
		if(!hasDrawJs) {
			var s = document.createElement('script');
			s.type = 'text/javascript';
			s.async = false;
			s.src = WIS_H5DRAW_PATH;
			s.charset = 'UTF-8';
			(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(s);
		}
		var wait = 100;
		var timerrr = setInterval(function(){	
			hasPaho = (typeof Paho !="undefined");
			hasDrawJs = (typeof WISDRAW !="undefined");
			if (hasPaho && hasDrawJs) {
				clearInterval(timerrr);
				opt_.drawFactory = WISDRAW();
				opt_.drawFactory.Init(document.getElementById("__wis_draw__"),
						document.getElementById("__wis_draw_fg__"),
						syncData,document.getElementById("__wis_bg_img__"),document.getElementById("__wis__sm__container__"));
				loadInfo();
			}
			wait--;
			if(wait <=0){
				clearInterval(timerrr);
				if(!hasPaho){
					opt_.failure("load ws.js fail");
				}else if(!hasDrawJs){
					opt_.failure("load draw.js fail");
				}
			}
		},10);
	}
	function LoadSwfObject ( ){
		if (typeof swfobject !="undefined") {
			loadFlush();
			return;
		}
		var s = document.createElement('script');
		s.type = 'text/javascript';
		s.async = false;
		s.src = 'http://cdn.aodianyun.com/wis/swfobject.js';
		s.charset = 'UTF-8';
		(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(s);
		var wait = 100;
		var timerrr = setInterval(function(){							
			if (typeof swfobject !="undefined") {
				clearInterval(timerrr);
				loadFlush();
				return;
			}
			wait--;
			if(wait <=0){
				clearInterval(timerrr);
				opt_.failure("load swfobject.js fail");
			}
		},10);
	}
	function loadFlush(){
		function callback(item){
			if( item.success ){
				var wait = 500;
				var timerrr = setInterval(function(){
					flash_obj = swfobject.getObjectById("__wis__");
					if(flash_obj && flash_obj.init){
						clearInterval(timerrr);
						flash_obj.init();
						window.__wis__syncDraw = syncData;
						//window.__onDocLoadComplete = onDocLoadComplete;
						opt_.drawFactory = flash_obj;
						loadInfo();
						return;
					}
					wait--;
					if(wait <=0){
						clearInterval(timerrr);
						opt_.failure("flash init fail");
					}
				},10);
			}else{
				opt_.failure("flash load fail");
			}
		}
		if(swfobject.getObjectById("__wis__")){
			callback({success:true});
			return
		}
		swfobject.embedSWF(WIS_FLASH_PATH, '__wis__flash__div__', "0", "0", "11.0.0", 
		WIS_FLASH_INSTALL_PATH, {id:"__wis__"}, {AllowScriptAccess:"always",wmode:"Transparent"},{id:"__wis__",name:"__wis__",align:"middle"},
		callback);
	}
	function checkDiff(){
		var now = new Date().getTime();
		if(now - opt_.preTime > opt_.pageDiff){
			opt_.preTime = now;
			return true;
		}
		return false;
	}

	return {
		Init:function(opt){
			opt_.api = opt.api;
			opt_.onCustomMessage = opt.onCustomMessage;
			opt_.wisId = opt.wisId;
			opt_.topic = null;
			opt_.updateUser =  opt.updateUser;
			opt_.orgWidth = opt.width;
			opt_.orgHeight = opt.height;
			opt_.width = opt.width;
			opt_.height = opt.height;
			opt_.onPageChange = opt.onPageChange;
			opt_.onConnect = opt.onConnect;
			opt_.onReconnect = opt.onReconnect;
			opt_.onConnectClose = opt.onConnectClose;
			opt_.onDocLoad = opt.onDocLoad;
			opt_.onResize = opt.onResize;
			opt_.flashId = opt.flashId;
			opt_.success = opt.success;
			opt_.failure = opt.failure;
			opt_.curPage = 0;
			opt_.container = opt.container;
			opt_.pageDiff = 150;
			opt_.preTime = new Date().getTime();
			if(canvasSupport()){
				opt_.useFlash = false;
				$("#"+opt_.container).prepend('<div id="__wis__sm__container__"  style="position: absolute; z-index: 4"></div>');
				$("#"+opt_.container).prepend('<canvas id="__wis_draw_fg__"  style="position: absolute; z-index: 3"></canvas>');
				$("#"+opt_.container).prepend('<canvas id="__wis_draw__" style="position: absolute; z-index: 2"></canvas>');
				$("#"+opt_.container).prepend('<img id="__wis_bg_img__"  style="position: absolute; z-index: 1"></img>');
				setTimeout(LoadWsAndDrawJs,100);
			}else{
				$("#"+opt_.container).prepend('<div id="__wis__flash__div__"></div>');
				opt_.useFlash = true;
				opt_.callBackMap = {};
				opt_.callBackIndex = 1;
				window.__call__wis__pageload = function(index,sused){
					cb  = opt_.callBackMap[index];
					delete opt_.callBackMap[index];
					if(cb){
						cb(sused);
					}
				}
				LoadSwfObject();
			}

		},
		NextPage:function(option){
			if(!opt_.loaded){
				if(option && option.failure)option.failure("文档服务加载中");
				return;
			}
			if(opt_.curPage == opt_.maxPage){
				if(option && option.failure)option.failure("已到达最后一页");
				return;
			}
			if(!checkDiff()){
				if(option && option.failure)option.failure("翻页太频繁了");
				return;
			}
			var page = Number(opt_.curPage)+1;
			syncAndShowPage(page,option);
		},
		PrevPage:function(option){
			if(!opt_.loaded){
				if(option && option.failure)option.failure("文档服务加载中");
				return;
			}
			if(opt_.curPage == 1) {
				if(option && option.failure)option.failure("已到达第一页");
				return;
			}
			if(!checkDiff()){
				if(option && option.failure)option.failure("翻页太频繁了");
				return;
			}
			var page = Number( opt_.curPage )-1;
			syncAndShowPage(page,option);
		},
		ToPage:function(page,option){
			if(!opt_.loaded){
				if(option && option.failure)option.failure("文档服务加载中");
				return;
			}
			if(page <= 0 || page >opt_.maxPage){
				if(option && option.failure)option.failure("页码不正确");
				return;
			}
			if(!checkDiff()){
				if(option && option.failure)option.failure("翻页太频繁了");
				return;
			}
			syncAndShowPage(page,option);
		},
		GetCurrentDoc:function(){
			if(!opt_.loaded){
				throw new Error("文档服务加载中") ;
			}
			return opt_.docId;
		},
		LineWidth:function(lw){
			if(!lw){
				lw = null;
			}
			if(opt_.drawFactory){
				return opt_.drawFactory.LineWidth(lw);
			}
			
		},
		FontSize:function(fs){
			if(!fs){
				fs = null;
			}
			if(opt_.drawFactory){
				return opt_.drawFactory.FontSize(fs);
			}
			
		},
		Loaded:function(){
			return opt_.loaded;
		},
		Color:function(co){
			if(!co){
				co = null;
			}
			if(opt_.drawFactory){
				return opt_.drawFactory.Color(co);
			}
			
		},
		SetDrawType:function(type){
			if(!opt_.loaded){
				throw new Error("文档服务加载中");
			}
			if(opt_.drawFactory){
				opt_.drawFactory.SetDrawType(type);
			}
		},
		AllowDraw:function( option ){
			if(!opt_.loaded){
				if(option.failure){
					option.failure("文档服务加载中");
				}
				return;
			}
			if(!!option.ballow){
				opt_.api.allowDraw({
					success:function(){
						if(opt_.drawFactory){
							opt_.drawFactory.AllowDraw(true);
							if(option.failure){
								option.failure(err);
							}
						}
						if(option.failure){
							option.failure("文档服务加载中");
						}
					},
					failure:function(err){
						if(option.failure){
							option.failure(err);
						}
					}
				});
			}else{
				if(opt_.drawFactory){
					return opt_.drawFactory.AllowDraw(false);
				}
			}
			
		},
		Clear:function(){
			if(!opt_.loaded){
				throw new Error("文档服务加载中") ;
			}
			syncData({cmd:"clear"});
			opt_.drawFactory.Clear();
		},
		SendCustomMessage:function(option){
			if(!option || !option.msg){
				throw new Error("参数错误") ;
			}
			if(typeof option.msg != "string"){
				if(opt_.useFlash){
					option.msg = opt_.drawFactory.JSONEncode(option.msg);
				}else{
					option.msg = JSON.stringify(option.msg);
				}
			}
			
			opt_.api.customMessage({
				wisId:opt_.wisId,
				body:option.msg,
				success:option.success,
				failure:option.failure,
			});
		},
		
		ChoseDoc:function(option){
			if( !option.wisId){
				option.wisId = opt_.wisId;
			} 
			opt_.api.choseDoc(option);
		},
		
		Resize:function(w,h){
			if(!opt_.loaded){
				throw new Error("文档服务加载中");
			}
			if(!!w){
				opt_.orgWidth = w;
			} 
			if(!!h){
				opt_.orgHeight = h;
			}
			resize();
			opt_.api.getHistory({
				wisId:opt_.wisId,
				success:function(data){
					ShowPage({
						success:function(){
							parseHistory(data);
						}
					});
					
				},
				failure:function(){
					ShowPage();
				}
			});
		},
		getClientid : function(){
			return clientid_;
		}
	}
}();